var mongoose = require('mongoose');
var fs = require('fs');

var schemas = require('../models/models.js')

//checks the unique ID sent as a query, and sends the IDE as a response
exports.getIde = function(req, res) {
	var uniqueID = parseInt(req.query.id);
	if(validIDs.indexOf(uniqueID) != -1) {
		fs.readFile('./public/html/ide.html', function(err, data) {
			if(err) {
				console.log(err);
				validIDs.splice(validIDs.indexOf(uniqueID), 1);
				res.send('Error in getIde - readFile');
				return
			}
			validIDs.splice(validIDs.indexOf(uniqueID), 1)
			res.send(data)
		})
	}
}
//get the Sorry! page for Firefox users
exports.getSorry = function(req, res) {
	fs.readFile('./public/html/sorry.html', function(err, data) {
		if(err) {
			console.log(err);
			res.send('Error in getSorry - readFile');
			return
		}
		res.send(data);
	})
}

//saves a session for user, takes a session= query
exports.saveSession = function(req, res) {
	console.log('arrivato')
	var newSession = mongoose.model('Session', schemas.SessionSchema);
	var data = new newSession({
		session : req.query.session
	})
	data.save()
	res.send(null)
}

//get a session for a user, takes a user= query
exports.getSession = function(req, res) {
	var newSession = mongoose.model('Session', schemas.SessionSchema);
	var session;
	newSession.find({}, function(err, found) {
		for(i in found) {
			session = JSON.parse(found[i].session)  //current session in the loop
			if(req.query.user == session.user) {
				found[i].remove()
				res.send(JSON.stringify(session))
			}
		}
		res.send('No session')
	})
}